#pragma once
#include <iostream>
#include <algorithm> 
#include <string>

const std::string blank_space_sep = " "; // 空格分隔符
const std::string protocal_sep = "\n";   // 协议分隔符
//"len"\n"message"\n

std::string Encode(std::string &content)
{
    std::string package = std::to_string(content.size());
    package += protocal_sep;
    package += content;
    package += protocal_sep;
    return package;
}

bool Decode(std::string &package, std::string *content)
{
    // 查找第一个换行符，分离出长度部分
    std::size_t pos = package.find('\n');
    if (pos == std::string::npos)
        return false; // 没找到长度分隔符，协议不完整

    std::string len_str = package.substr(0, pos);

    if (len_str.empty() || !std::all_of(len_str.begin(), len_str.end(), ::isdigit))
    {
        std::cerr << "Decode error:len_str is not vaild number,content: [" << len_str << "]\n";
        return false;
    }

    //std::size_t len = std::stoi(len_str);
    std::size_t len = 0;
     try {
        len = std::stoi(len_str);
    } catch (const std::exception &e) {
        std::cerr << "Decode error: stoi fail:" << e.what() << "\n";
        return false;
    }

    // 完整协议总长度 = len_str + '\n' + message + '\n'
    std::size_t total_len = pos + 1 + len + 1;

    if (package.size() < total_len)
        return false; // 协议数据还没接收完整

    // 获取消息内容
    *content = package.substr(pos + 1, len);

    // 检查最后一位是不是\n，避免粘包出错
    if (package[pos + 1 + len] != '\n')
        return false;
    package.erase(0, total_len);
    return true;
}